package com.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.domain.Cart;
import com.util.JdbcUtils;

/**
 * 
 * 功能描述：购物车业务方法
 * 
 * Version： 1.0
 * 
 * date： 2016年6月24日 上午10:15:22
 * 
 * @author：XiaoBingBy
 *
 */
public class daoCar {

	/**
	 * 插入数据到购物车  如果有重复++1
	 * @param username
	 * @param goods_id
	 * @param carId 
	 * @param i 
	 * @return 返回是否插入成功标志
	 */
	public Integer instartInfoGoods(String username, String goods_id) {
		QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
		int update = 0;
		
		if (isExistGoodsId(goods_id)) {
			String updatesql="update cart set quantity=quantity+1 where goods_id=?";
			try {
				update = queryRunner.update(updatesql, goods_id);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}else{
			String sql = "INSERT INTO `m-ss`.`cart` (`username`, `goods_id`, `quantity`) VALUES (?, ?, ?)" ;
			try {
				update = queryRunner.update(sql, new Object[]{username, goods_id, 1});
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return update;
	}
	
	/**
	 * 判断商品 goods_id 在 cart 数据库中是否存在
	 * @param goods_id
	 * @return true OR false
	 */
	public boolean isExistGoodsId(String goods_id) {
		QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
		
		String sql1="SELECT cart.goods_id FROM cart WHERE cart.goods_id = ?";
		Cart query = null;
		try {
			query = queryRunner.query(sql1, new BeanHandler<>(Cart.class), goods_id);
		} catch (SQLException e1) {
			e1.printStackTrace();
			return false;
		}
		
		if (query!=null) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 
	 * @param username 
	 * @return
	 */
	public List<Cart> selectAllCar(String username) {
		QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
		
		String sql = "SELECT * FROM cart WHERE username = ?";
		try {
			List<Cart> query = queryRunner.query(sql, new BeanListHandler<>(Cart.class), username);
			return query;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 清空这个用户的购物车
	 * @param username
	 * @return
	 */
	public Integer deleteAllCar(String username) {
		QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
		
		String sql = "DELETE FROM cart WHERE username = ?";
		try {
			return queryRunner.update(sql, username);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

}
